package com.rundatop.wx.controller;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.rundatop.core.util.ResponseUtil;
import com.rundatop.dao.model.User;
import com.rundatop.wx.config.WxProperties;
import com.rundatop.wx.service.UserService;
import com.rundatop.wx.service.UserTokenManager;
import com.rundatop.wx.wechat.WxAuthService;
import com.rundatop.wx.wechat.req.WeChatUserInfo;
import com.rundatop.wx.wechat.utils.WxHelper;


/**
 * 微信网页授权登录相关方法
 */
@RestController
@RequestMapping("/wx/web/auth")
public class WxWebAuthController extends BaseController {
    private final Log logger = LogFactory.getLog(WxWebAuthController.class);

    @Autowired
	private HttpServletRequest request;
    @Autowired
	private HttpServletResponse response;
    @Autowired
	private WxAuthService wxAuthService;
	@Autowired
	private WxProperties wxProperties;
	@Autowired
    private UserService userService;

	/**
	 *
	 * @param webType 3页面点击授权
	 * @return
 	 * @throws IOException 
	 */
	@RequestMapping("/{webType}")
	public ModelAndView redirect(@PathVariable("webType") int webType, @Param("flag") String flag) throws IOException {
		if(webType == 3){
			String refer = request.getHeader("Referer");
			logger.info(refer);
			request.getSession().setAttribute("redirectUrl", refer);
		}
		return new ModelAndView("redirect:"+buildRedirectUrl(flag));
	}
	
	/**
	 *
	 * @param webType 3页面点击授权
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/redirectUrl/{webType}")
	public String redirectUrl(@PathVariable("webType") int webType) throws IOException {
		if(webType == 3){
			String refer = request.getHeader("Referer");
			logger.info(refer);
			request.getSession().setAttribute("redirectUrl", refer);
		}
		return buildRedirectUrl();
	}

	/**
	 *  使用即答服务号授权
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	private String buildRedirectUrl() throws UnsupportedEncodingException {
		//TODO 此处应根据实际的域名修改
		String redirectUrl = "http://" + request.getServerName() + "/wx/web/auth/code";
		System.out.println(redirectUrl);
		String redirect_url = String.format(WxHelper.WX_LOGIN_URL, wxProperties.getAppId(),
						URLEncoder.encode(redirectUrl, "UTF8"));
		System.out.println(URLEncoder.encode(redirectUrl, "UTF8"));
		System.out.println(redirect_url);
		logger.info(redirect_url);
		return redirect_url;
	}
	
	/**
	 *  使用即答服务号授权
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	private String buildRedirectUrl(String flag) throws UnsupportedEncodingException {
		//TODO 此处应根据实际的域名修改
		String redirectUrl = "http://" + request.getServerName() + "/wx/web/auth/code?flag="+flag;
		System.out.println(redirectUrl);
		String redirect_url = String.format(WxHelper.WX_LOGIN_URL, wxProperties.getAppId(),
						URLEncoder.encode(redirectUrl, "UTF8"));
		System.out.println(URLEncoder.encode(redirectUrl, "UTF8"));
		System.out.println(redirect_url);
		logger.info(redirect_url);
		return redirect_url;
	}
    
	/**
	 * 授权回调页面
	 * @param code
	 * @param state
	 * @param model
	 * @return
	 */
    @RequestMapping("/code")
 	public ModelAndView code(String code,String state, Model model, String flag) {
    	try {
 			logger.info("wx auth state : {}"+ state);
 			WeChatUserInfo wxUser = wxAuthService.auth(code);
 			if (wxUser == null){
 				return new ModelAndView("redirect:/index.html#/pages/index/index");
 			} else {
 				User dbuser = userService.selectByKey(wxUser.getOpenid());
 				if(dbuser!=null) {
 					dbuser.setNickName(wxUser.getNickname());
 					dbuser.setUpdateTime(new Date());
 					userService.updateByPrimaryKeySelective(dbuser);
 				} else {
// 					//新增用户
 					dbuser = new User();
 					dbuser.setId(wxUser.getOpenid());
 					dbuser.setNickName(wxUser.getNickname());
 					dbuser.setSex(wxUser.getSex());
 					dbuser.setAddrProvince(wxUser.getProvince());
 					dbuser.setAddrCity(wxUser.getCity());
 					dbuser.setHeadImg(wxUser.getHeadimgurl());
 					dbuser.setUpdateTime(new Date());
 					int ok=userService.save(dbuser);
 					if(ok!=1) throw new RuntimeException("存储用户信息失败");
 				}
 				 // token
 		        String token = UserTokenManager.generateToken(wxUser.getOpenid());
 		       return new ModelAndView("redirect:/index.html#/pages/my/checkToken?token="+token+"&flag="+flag);
 			}
 		} catch (Exception exception) {
 			exception.printStackTrace();
 			return new ModelAndView("redirect:/index.html#/pages/index/index");
 		}
    }
}
